import axios from 'axios'
import qs from 'qs'
import Router from '../router'
import store from '@/store/store'

let _axios = axios.create({
  // baseURL: '/api',
  withCredentials: true,
  timeout: 0,
  headers: { 'Content-Type':'application/json' },
  transformRequest: [function (data) {
    if (data && data.isUpload) return data.formData
    else return data ? JSON.stringify(data) : JSON.stringify({})
  }],
  
  paramsSerializer: function (params) {
    return qs.stringify(params)
  }
})

// 请求拦截器
_axios.interceptors.request.use(config => {
  config.headers.Accept = 'application/json'
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
_axios.interceptors.response.use(res => {
  if (res.config.params && res.config.params.requestType && res.config.params.requestType === 'blob') {
    // let urlPdf = window.URL.createObjectURL(new Blob([res.data]))
    return res.data
  } else {
    if (res.data.code === 0 || (res.data.ResultSet && res.data.ResultSet.status == 0)) return res.data
    else {
      if (res.data.ResultSet && res.data.ResultSet.status === 20000) {
        store.dispatch('changeLogin', { show: true })
      }
      return Promise.reject(res.data)
    }
  }
}, err => {
  let originalRequest = err.config
  if (err.code === 'ECONNABORTED' && err.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
    return Promise.reject('请检查网络再重新连接！')
  }
  return Promise.reject(err.data)
})

export default _axios
